<template>
  <div>
    <el-form :model="templateObj" class="temp-form">
      <!-- 入参模板 -->
      <el-row class="input-temp tepm-item">
        <el-row>
          <el-col :span="14">
            <el-form-item label-width="auto" label="模板定义" />
          </el-col>
          <el-col :span="4" class="operater">
            <div class="item">
              <i class="el-icon-plus add-icon"></i>
              <span class="select-items">操作选项</span>
            </div>
            <ul class="items">
              <li @click="openAddRecordPage">添加模板</li>
              <li @click="updateTemplate">修改模板</li>
              <li @click="delTemplate">删除模板</li>
            </ul>
          </el-col>
          <el-col :span="6" class="fxh-templates">
            <el-select v-model="templateObj.currTemplate" placeholder="请添加" @change="changeTemplate">
              <el-option v-for="item in templateObj.templates" :key="item.id" :label="item.name" :value="item">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-form-item label="" class="temp-info">
          <el-input type="textarea" readonly v-model="templateObj.templateVal" :value="templateObj.templateVal" class="output-value" :rows="rows" resize="none"></el-input>
        </el-form-item>
      </el-row>
    </el-form>
    <!-- 添加修改记录的dialog -->
    <el-dialog title="添加模板" :visible.sync="showUpdateItem" class="update-record" center>
      <div slot="title" class="dialog-title">
        <h1>添加/修改模板</h1>
      </div>
      <el-form :model="templateObj" label-width="70px" class="record-form">
        <el-form-item label="模板名称">
          <el-input v-model="templateObj.record.title" autocomplete="off" class="input-title"></el-input>
        </el-form-item>
        <el-form-item label="模板内容">
          <el-input v-model="templateObj.record.content" :rows="rows" type="textarea" autocomplete="off" class="record-content" resize="none"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changeShowUpdateItem">取 消</el-button>
        <el-button type="primary" @click="saveUpdateRecord">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { showPrompt } from '../../../../js/mixins/inputPage'
import { request } from "@/js/_x/utils/request"
import { mapState } from 'vuex'

export default {
  name: "ParamTemplate",
  computed: {
    ...mapState({
      currProject: state => state.aside.currentProject
    })
  },
  watch: {
    currProject: function () {
      this.templateObj.currTemplate = ""
      this.templateObj.templateVal = ""
      this.templateObj.templates = []
      this.getTemplates()
      /* this.getTemplateDetail() */
    }
  },
  data () {
    return {
      rows: 20,
      showUpdateItem: false,
      updateFlag: false,
      templateObj: {
        record: {
          title: "",
          content: ""
        },
        desc: "",
        templates: [],
        currTemplate: "",
        /* 模板详细数据 */
        templateVal: ""
      }
    };
  },
  methods: {
    /* 点击确定是保存数据到后台 */
    saveUpdateRecord () {
      // 验证
      if (!this.templateObj.record.title) {
        this.$message({ type: "error", message: "名称不能为空!" })
        return
      }
      try {
        JSON.parse(this.templateObj.record.content)
      } catch (error) {
        this.$message({ type: "error", message: "请输入json格式的数据!" })
        return;
      }
      // 区分是修改还是新增
      if (this.updateFlag) {
        // 说明是修改
        this.updateTemplateFun(this.templateObj.record.title, this.templateObj.currTemplate)
      } else {
        // 新增
        this.saveRecord()
      }
    },
    saveRecord () {
      let params = {
        "projectName": this.currProject,
        "name": this.templateObj.record.title,
        "data": this.templateObj.record.content
      }
      request("api/interface/template/add_template", params, resp => {
        if (resp.result) {
          this.$message({ type: "success", message: "操作成功!" })
          /* 关闭弹框 */
          this.changeShowUpdateItem()
          /* 刷新数据 */
          this.getTemplates()
        } else {
          this.$message({ type: "error", message: resp.message })
        }
      }).catch(error => {
        console.log(error)
        this.$message({ type: "error", message: "后台异常,操作失败!" })
      })
    },
    openAddRecordPage () {
      this.updateFlag = false
      this.changeShowUpdateItem()
    },
    changeShowUpdateItem () {
      if (!this.showUpdateItem) {
        /* 清空模板数据 */
        this.templateObj.record.title = ""
        this.templateObj.record.content = ""
      }
      this.showUpdateItem = !this.showUpdateItem;
    },
    /* 模板列表数据获取 */
    getTemplates () {
      const params = {
        projectName: this.currProject
      }
      request("api/interface/template/get_templates", params, resp => {
        console.log(resp)
        if (resp.result && resp) {
          this.templateObj.templates = resp.data.map(item => item.replace(".json", ""))
          if (!this.templateObj.currTemplate) {
            this.templateObj.currTemplate = this.templateObj.templates[0];
          }
          this.getTemplateDetail()
        } else {
          this.templates = []
        }
      }).catch(error => {
        console.log(error)
        this.templates = []
      })
    },
    /* 根据模板名字获取详情数据 */
    getTemplateDetail () {
      let params = {
        projectName: this.currProject,
        name: this.templateObj.currTemplate
      }
      request("api/interface/template/get_template_detail", params, resp => {
        console.log(resp)
        if (resp.result) {
          this.templateObj.templateVal = JSON.stringify(resp.data, null, 2)
        } else {
          this.templateObj.templateVal = ""
        }
      }).catch(error => {
        console.log(error)
        this.templateObj.templateVal = ""
      })
    },
    /* 下拉框数据改变回调获取模板数据 */
    changeTemplate (value) {
      this.getTemplateDetail()
    },
    addTemplate () {
      showPrompt(this, { message: "输入模板名称：", title: "添加模板" }, value => {
        if (!value) {
          this.$message({ type: "error", message: "名称不能为空!" })
          return
        }
        let params = {
          "projectName": this.currProject,
          "name": value,
          "data": this.templateObj.templateVal
        }
        request("api/interface/template/add_template", params, resp => {
          if (resp.result) {
            this.$message({ type: "success", message: "添加成功!" })
            /* 刷新数据 */
            this.getTemplates()
          } else {
            this.$message({ type: "error", message: resp.message })
          }
        }).catch(error => {
          console.log(error)
          this.$message({ type: "error", message: "后台异常,添加失败!" })
        })
      })
    },
    /* 真正请求后台数据的接口 newName: 对应模板新名称 data: 模板数据 */
    updateTemplateFun (newName, oldName) {
      if (!newName) {
        this.$message({ type: "error", message: "名称不能为空!" })
        return
      }
      let params = {
        "projectName": this.currProject,
        "oldName": oldName,
        "name": newName,
        "data": this.templateObj.record.content
      }
      request("api/interface/template/update_template", params, resp => {
        if (resp.result) {
          this.updateFlag = false
          /* 关闭弹框 */
          this.changeShowUpdateItem()
          this.$message({ type: "success", message: "操作成功!" })
          this.templateObj.currTemplate = newName
          // 刷新数据
          this.getTemplates()
        } else {
          this.$message({ type: "error", message: resp.message })
        }
      }).catch(error => {
        console.log(error)
        this.$message({ type: "error", message: "后台异常,操作失败!" })
      })
    },
    /* 修改模板内容 */
    updateTemplate (name) {
      // 开启修改标志
      this.updateFlag = true
      // 打开弹窗
      this.changeShowUpdateItem()
      // 第一步，获取模板数据
      this.templateObj.record.title = this.templateObj.currTemplate
      this.templateObj.record.content = this.templateObj.templateVal
    },
    delTemplate () {
      this.$confirm("确认删除模板?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let params = {
          projectName: this.currProject,
          name: this.templateObj.currTemplate
        };
        request("api/interface/template/delete_template", params, resp => {
          if (resp.result) {
            this.$message.success("删除成功!");
            this.templateObj.currTemplate = ""
            this.getTemplates();
          } else {
            this.$message.error(`删除失败!原因: ${resp.message}`);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(`后台异常,删除失败!`);
        });
      });
    }
  },
  mounted () {
  }
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/mixin.scss";
@import "~@/assets/styles/home/content/ParamTemplate";
</style>
